package com.wxzhou.wangzhuan.config;


import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

import java.time.Instant;

@Provider
public class GlobalExceptionMapper implements ExceptionMapper<NotFoundException> {
    @Context
    private UriInfo uriInfo; // 可直接注入获取路径/查询参数

    @Override
    public Response toResponse(NotFoundException exception) {
        Response response = exception.getResponse();
        String path = uriInfo.getPath();
        // 判断是否是 API 请求
        if (isApiRequest(path) && response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
            return handleApiNotFound(path);
        } else {
            return handlePageNotFound();
        }
    }

    private boolean isApiRequest(String path) {
        return path != null && (path.startsWith("/api/") || path.startsWith("/v1/") || path.startsWith("/v2/"));
    }

    private Response handleApiNotFound(String path) {
        var errorResponse = new ApiErrorResponse(
                "NOT_FOUND",
                "请求的资源不存在",
                path,
                Instant.now()
        );

        return Response.status(Response.Status.NOT_FOUND)
                .entity(errorResponse)
                .type("application/json")
                .build();
    }

    private Response handlePageNotFound() {
        String html = """
                <!DOCTYPE html>
                <html><meta charset="UTF-8">
                <head><title>404 - 页面未找到</title></head>
                <body>
                    <h1>404 - 页面未找到</h1>
                    <p>抱歉，您访问的页面不存在</p>
                </body>
                </html>
                """;

        return Response.status(Response.Status.NOT_FOUND)
                .entity(html)
                .type("text/html")
                .build();
    }

    // 内部类用于 JSON 响应
    public static class ApiErrorResponse {
        public String error;
        public String message;
        public String path;
        public Instant timestamp;

        public ApiErrorResponse(String error, String message, String path, Instant timestamp) {
            this.error = error;
            this.message = message;
            this.path = path;
            this.timestamp = timestamp;
        }
    }


}